package cn.ibizlab.businesscentral.centralapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.base.domain.Legal;
import cn.ibizlab.businesscentral.core.base.service.ILegalService;
import cn.ibizlab.businesscentral.core.base.filter.LegalSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"法人" })
@RestController("CentralApi-legal")
@RequestMapping("")
public class LegalResource {

    @Autowired
    public ILegalService legalService;

    @Autowired
    @Lazy
    public LegalMapping legalMapping;

    @PreAuthorize("hasPermission(this.legalMapping.toDomain(#legaldto),'iBizBusinessCentral-Legal-Create')")
    @ApiOperation(value = "新建法人", tags = {"法人" },  notes = "新建法人")
	@RequestMapping(method = RequestMethod.POST, value = "/legals")
    public ResponseEntity<LegalDTO> create(@RequestBody LegalDTO legaldto) {
        Legal domain = legalMapping.toDomain(legaldto);
		legalService.create(domain);
        LegalDTO dto = legalMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.legalMapping.toDomain(#legaldtos),'iBizBusinessCentral-Legal-Create')")
    @ApiOperation(value = "批量新建法人", tags = {"法人" },  notes = "批量新建法人")
	@RequestMapping(method = RequestMethod.POST, value = "/legals/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<LegalDTO> legaldtos) {
        legalService.createBatch(legalMapping.toDomain(legaldtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "legal" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.legalService.get(#legal_id),'iBizBusinessCentral-Legal-Update')")
    @ApiOperation(value = "更新法人", tags = {"法人" },  notes = "更新法人")
	@RequestMapping(method = RequestMethod.PUT, value = "/legals/{legal_id}")
    public ResponseEntity<LegalDTO> update(@PathVariable("legal_id") String legal_id, @RequestBody LegalDTO legaldto) {
		Legal domain  = legalMapping.toDomain(legaldto);
        domain .setLegalid(legal_id);
		legalService.update(domain );
		LegalDTO dto = legalMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.legalService.getLegalByEntities(this.legalMapping.toDomain(#legaldtos)),'iBizBusinessCentral-Legal-Update')")
    @ApiOperation(value = "批量更新法人", tags = {"法人" },  notes = "批量更新法人")
	@RequestMapping(method = RequestMethod.PUT, value = "/legals/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<LegalDTO> legaldtos) {
        legalService.updateBatch(legalMapping.toDomain(legaldtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.legalService.get(#legal_id),'iBizBusinessCentral-Legal-Remove')")
    @ApiOperation(value = "删除法人", tags = {"法人" },  notes = "删除法人")
	@RequestMapping(method = RequestMethod.DELETE, value = "/legals/{legal_id}")
    public ResponseEntity<Boolean> remove(@PathVariable("legal_id") String legal_id) {
         return ResponseEntity.status(HttpStatus.OK).body(legalService.remove(legal_id));
    }

    @PreAuthorize("hasPermission(this.legalService.getLegalByIds(#ids),'iBizBusinessCentral-Legal-Remove')")
    @ApiOperation(value = "批量删除法人", tags = {"法人" },  notes = "批量删除法人")
	@RequestMapping(method = RequestMethod.DELETE, value = "/legals/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        legalService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.legalMapping.toDomain(returnObject.body),'iBizBusinessCentral-Legal-Get')")
    @ApiOperation(value = "获取法人", tags = {"法人" },  notes = "获取法人")
	@RequestMapping(method = RequestMethod.GET, value = "/legals/{legal_id}")
    public ResponseEntity<LegalDTO> get(@PathVariable("legal_id") String legal_id) {
        Legal domain = legalService.get(legal_id);
        LegalDTO dto = legalMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取法人草稿", tags = {"法人" },  notes = "获取法人草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/legals/getdraft")
    public ResponseEntity<LegalDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(legalMapping.toDto(legalService.getDraft(new Legal())));
    }

    @ApiOperation(value = "检查法人", tags = {"法人" },  notes = "检查法人")
	@RequestMapping(method = RequestMethod.POST, value = "/legals/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody LegalDTO legaldto) {
        return  ResponseEntity.status(HttpStatus.OK).body(legalService.checkKey(legalMapping.toDomain(legaldto)));
    }

    @PreAuthorize("hasPermission(this.legalMapping.toDomain(#legaldto),'iBizBusinessCentral-Legal-Save')")
    @ApiOperation(value = "保存法人", tags = {"法人" },  notes = "保存法人")
	@RequestMapping(method = RequestMethod.POST, value = "/legals/save")
    public ResponseEntity<Boolean> save(@RequestBody LegalDTO legaldto) {
        return ResponseEntity.status(HttpStatus.OK).body(legalService.save(legalMapping.toDomain(legaldto)));
    }

    @PreAuthorize("hasPermission(this.legalMapping.toDomain(#legaldtos),'iBizBusinessCentral-Legal-Save')")
    @ApiOperation(value = "批量保存法人", tags = {"法人" },  notes = "批量保存法人")
	@RequestMapping(method = RequestMethod.POST, value = "/legals/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<LegalDTO> legaldtos) {
        legalService.saveBatch(legalMapping.toDomain(legaldtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Legal-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Legal-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"法人" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/legals/fetchdefault")
	public ResponseEntity<List<LegalDTO>> fetchDefault(LegalSearchContext context) {
        Page<Legal> domains = legalService.searchDefault(context) ;
        List<LegalDTO> list = legalMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-Legal-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-Legal-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"法人" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/legals/searchdefault")
	public ResponseEntity<Page<LegalDTO>> searchDefault(@RequestBody LegalSearchContext context) {
        Page<Legal> domains = legalService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(legalMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

